<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>项目总览</span>
        </div>
      </template>
      <div class="statistic box">
        <div class="title">{{ year }}年</div>
        <el-row>
          <el-col :span="12">
            <el-statistic title="总制作数" :value="totalProduct" />
          </el-col>
          <el-col :span="12">
            <el-statistic :value="totalMoney">
              <template #title>
                <div style="display: inline-flex; align-items: center">
                  总经营额
                  <el-popover
                    placement="top-start"
                    title="提示"
                    :width="200"
                    trigger="hover"
                    content="该数据仅代表项目完成，不代表经营到账"
                  >
                    <template #reference>
                      <el-icon style="margin-left: 4px;cursor:pointer" :size="12">
                        <warning />
                      </el-icon>
                    </template>
                  </el-popover>
                </div>
              </template>
            </el-statistic>
          </el-col>
        </el-row>
      </div>
      <el-row :gutter="20" type="flex" justify="center">
        <el-col :span="24" :md="12" :lg="8">
          <div class="internal box">
            <div
              id="chart"
              style="
                height: 500px;
                width: 100%;
                padding-top: 30px;
                background: #fff;
              "
            ></div>
          </div>
        </el-col>
        <el-col :span="24" :md="12" :lg="8">
          <div class="business box">
            <div class="subTitle">经营项目</div>
            <p v-for="(o, index) in businessData" :key="o">
              {{ index + 1 }}. {{ o.product_name }}
              <span style="color: #dd5353; font-weight: bold"
                >（{{ o.money }}）</span
              >
            </p>
          </div>
        </el-col>
        <el-col :span="24" :md="12" :lg="8">
          <div class="personnel box" v-if="tool.isAdmin()">
            <div class="subTitle">
              <span
                @click="nameClick()"
                style="cursor: pointer; text-decoration: underline"
                >人员情况</span
              >
            </div>
            <div class="person">
              <el-popover
                v-for="item in personData"
                :key="item.member"
                placement="top"
                width="200"
                trigger="click"
              >
                <div v-html="generateContent(item.projects)"></div>
                <template #reference>
                  <el-tag :type="item.type" effect="dark">{{
                    item.member
                  }}</el-tag>
                </template>
              </el-popover>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <!-- Image Dialog -->
    <div class="tc" v-if="showImage" :visible.sync="showImage">
      <el-icon class="close" color="white" @click="showImage = false"
        ><Close
      /></el-icon>
      <div class="tcSource">
        <img
          :src="selectedImage"
          :style="imageStyle"
          style="transition: all 0.5s"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import * as eCharts from 'echarts'
import workApi from '../api/work'
import userApi from '../api/user'
import tool from '../tools/tool'
import { useRouter } from 'vue-router'
const router = useRouter()

const years = ref()
const year = ref()
const eChartData = ref([]) //项目统计图
const businessData = ref([]) //经营项目
const personData = ref([]) //人员情况
const totalProduct = ref(0)
const totalMoney = ref(0)
const isAdmin = ref(false)

// 获取全局变量
const baseURL = window.globalConfig.baseURL

onMounted(async () => {
  const yearRes = await workApi.getDistinctYears()
  years.value = yearRes.data
  //默认今年
  const currentYear = new Date().getFullYear()
  year.value = currentYear

  getInternalList()
  getBusinessList()
  getPersonList()
})

const getInternalList = async () => {
  const data = {
    year: year.value,
  }
  const res = await workApi.getCount(data)

  eChartData.value = Object.assign([], res.data)

  // 遍历每行数据，累加到总和行
  for (const row of eChartData.value) {
    totalProduct.value += row.product_count || 0
    totalMoney.value += row.money || 0
  }

  // 初始化图表
  const chart = eCharts.init(document.getElementById('chart'))

  // 初始数据
  const eData = []
  for (let i = 0; i < eChartData.value.length; ++i) {
    eData.push({
      name: eChartData.value[i].department_name,
      value: eChartData.value[i].product_count,
    })
  }
  //从大到小排序
  eData.sort((a, b) => b.value - a.value)

  // 配置项
  const options = {
    title: {
      text: '项目统计图',
      left: 'center',
      textStyle: {
        fontSize: 18, // 设置字体大小
        fontWeight: 'bold', // 设置字体粗细
        color: '#333', // 设置字体颜色
        fontFamily: 'Microsoft YaHei', // 设置字体为微软雅黑
      },
    },
    grid: {
      left: '3%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      max: 'dataMax',
    },
    yAxis: {
      type: 'category',
      data: eData.map((item) => item.name),
      inverse: true,
      animationDuration: 300,
      animationDurationUpdate: 300,
    },
    series: [
      {
        realtimeSort: true,
        type: 'bar',
        data: eData.map((item) => item.value),
        label: {
          show: true,
          position: 'right',
          valueAnimation: true,
        },
      },
    ],
  }

  // 使用刚指定的配置项和数据显示图表。
  chart.setOption(options)
}

const getBusinessList = async () => {
  const data = {
    year: year.value,
  }
  const res = await workApi.getBusinessList(data)
  const rawData = res.data
  // 遍历 businessData 中的每个对象
  const transformedData = rawData.map((item) => {
    // 判断 money 是否为有效数字
    const moneyValue = parseFloat(item.money)
    if (!isNaN(moneyValue)) {
      // 将 money 转换为万元形式
      item.money = (moneyValue / 10000).toFixed(2) + '万元'
    }

    return item
  })
  businessData.value = transformedData
}

const getPersonList = async () => {
  const res = await workApi.getPersonList();
  // 处理res.data中的member
  const membersData = {};

  res.data.forEach((item) => {
    // 跳过progress为100的项
    if (item.progress === "100") {
      return;
    }

    // 将成员字符串拆分为数组
    const members = item.member.split(',').map((member) => member.trim());

    // 遍历成员数组，创建新的对象
    members.forEach((member) => {
      if (!membersData[member]) {
        membersData[member] = [];
      }

      // 将项目信息加入成员对应的数组
      membersData[member].push({
        product_name: item.product_name,
        department_name: item.department_name,
        work_date: item.work_date,
      });
    });
  });

  const res1 = await userApi.getUserList() //获取所有用户列表
  const allPerson = res1.data

  // 遍历所有人员数组，为不在 membersData 中的人员生成空数组
  allPerson.forEach((person) => {
    const name = person.name

    if (!membersData[name] && parseInt(person.role) < 9) {
      membersData[name] = []
    }
  })

  // 新增：为每个成员添加 type 字段
  Object.keys(membersData).forEach((member) => {
    const projects = membersData[member]
    if (projects.length > 3) {
      membersData[member].type = 'danger'
    } else if (projects.length <= 3 && projects.length > 0) {
      membersData[member].type = 'success'
    } else {
      membersData[member].type = 'info'
    }
  })

  personData.value = Object.keys(membersData).map((member) => ({
    member,
    projects: membersData[member],
    type: membersData[member].type,
  }))

  console.log(personData.value)
}

const generateContent = (projects) => {
  if (projects && projects.length > 0) {
    return projects
      .map((project, index) => {
        return `${index + 1}. ${project.product_name}`
      })
      .join('<br/>')
  } else {
    return '暂无项目'
  }
}

const nameClick = async () => {
  router.push({
    path: '/member_report',
  })
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-col {
  text-align: center;
}

.box {
  position: relative;
  border: 2px solid #c6cbcf;
  border-radius: 10px;
  padding: 30px 10px;
  margin-top: 10px;
}

.statistic .title {
  font-size: 24px;
  font-weight: bold;
  padding: 10px;
  background-color: #fff;
  z-index: 2;
  position: absolute;
  top: -27px;
  left: 50%;
  margin-left: -60px;
  color: #dd5353;
}

.subTitle {
  font-family: 'Microsoft YaHei';
  font-weight: bold;
  font-size: 18px;
  color: #333;
}

.business {
  max-height: 470px;
  overflow: auto;
}

.business p {
  text-align: left;
  background: white;
  box-shadow: -1px 2px 13px 3px #e3e3e3;
  padding: 10px;
  border-radius: 5px;
}

.internal {
  padding: 0;
}

.box-card {
  width: 100%;
}

.person {
  margin-top: 20px;
}

.time {
  font-size: 12px;
  color: #999;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-card {
  height: 100%;
  text-align: center;
}

.el-tag {
  margin: 5px;
  cursor: pointer;
  width: 70px;
  height: 30px;
}

.el-popover {
  white-space: pre-wrap;
}

.tc {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.7);
}

.tc img {
  width: 100%;
  height: auto;
  margin: auto;
}

.tc .close {
  position: fixed;
  top: 40px;
  left: 50%;
  width: 50px;
  height: 50px;
  cursor: pointer;
  margin-left: 300px;
}

.tc .close svg {
  width: 100%;
  height: 100%;
}

.tc .tcSource {
  width: 500px;
  height: 90vh;
  overflow: auto;
  margin: auto;
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
}
@media screen and (max-width: 768px) {
  .el-row {
    margin-right: 0;
    margin-left: 0;
  }

  .el-col {
    width: 100%;
  }
}
</style>
